package com.jiangjie.powplugin;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.util.ArrayMap;

import androidx.annotation.NonNull;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import io.flutter.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** PowpluginPlugin */
public class PowpluginPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private static final String ACCELEROMETER_CHANNEL_NAME =
          "powplugin/sensors/accelerometer";
  private static final String GYROSCOPE_CHANNEL_NAME = "powplugin/sensors/gyroscope";
  private static final String USER_ACCELEROMETER_CHANNEL_NAME =
          "powplugin/sensors/user_accel";

  static private EventChannel _accelerometerChannel;
  static private EventChannel _userAccelChannel;
  static private EventChannel _gyroscopeChannel;
  private Context context;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "powplugin");
    channel.setMethodCallHandler(this);



    context = flutterPluginBinding.getApplicationContext();
    BinaryMessenger messenger = flutterPluginBinding.getBinaryMessenger();

    _accelerometerChannel = new EventChannel(messenger, ACCELEROMETER_CHANNEL_NAME);
    final StreamHandlerImpl accelerationStreamHandler =
            new StreamHandlerImpl(
                    (SensorManager) context.getSystemService(context.SENSOR_SERVICE),
                    Sensor.TYPE_ACCELEROMETER);
    _accelerometerChannel.setStreamHandler(accelerationStreamHandler);

    _userAccelChannel = new EventChannel(messenger, USER_ACCELEROMETER_CHANNEL_NAME);
    final StreamHandlerImpl linearAccelerationStreamHandler =
            new StreamHandlerImpl(
                    (SensorManager) context.getSystemService(context.SENSOR_SERVICE),
                    Sensor.TYPE_LINEAR_ACCELERATION);
    _userAccelChannel.setStreamHandler(linearAccelerationStreamHandler);

    _gyroscopeChannel = new EventChannel(messenger, GYROSCOPE_CHANNEL_NAME);
    final StreamHandlerImpl gyroScopeStreamHandler =
            new StreamHandlerImpl(
                    (SensorManager) context.getSystemService(context.SENSOR_SERVICE),
                    Sensor.TYPE_GYROSCOPE);
    _gyroscopeChannel.setStreamHandler(gyroScopeStreamHandler);
  }

  public static void registerWith(Registrar registrar) {
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "powplugin");
    channel.setMethodCallHandler(new PowpluginPlugin());
  }
  private void teardownEventChannels() {
    _accelerometerChannel.setStreamHandler(null);
    _userAccelChannel.setStreamHandler(null);
    _gyroscopeChannel.setStreamHandler(null);
  }


  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else if (call.method.equals("generateExcel")) {
      if (call.arguments instanceof ArrayList) {
        ArrayList dataArr = (ArrayList) call.arguments;

        Log.d(this.getClass().toString(), String.format("原生拿到了%d条数据，处理中", dataArr.size()));
        String filepath = context.getExternalCacheDir() + "/tmp.xlsx";
        Log.d(this.getClass().toString(), "文件名："+filepath);
        File file = new File(filepath);
        if (file.exists()) {
          Boolean delres = file.delete();
          Log.d(this.getClass().toString(), "把原来的文件删掉了，成功了吗："+delres);
        }
        OutputStream outputStream;
        try {
          outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
          e.printStackTrace();
          return;
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Sheet1");

        ArrayList<String> keys = null;

        for (int dataIndex = 0; dataIndex < dataArr.size(); dataIndex++) {
          HashMap<String, Object> ondic = (HashMap<String, Object>) dataArr.get(dataIndex);
          if (ondic instanceof Map) {
            ArrayList<String> allKeys =new ArrayList<>( ondic.keySet());
            if (dataIndex == 0) {
              Log.d(this.getClass().toString(), "写入 title");
              keys = allKeys;//保存所有的标题
              HSSFRow titleRow = sheet.createRow(0);
              for (int titleIndex = 0; titleIndex < keys.size(); titleIndex++) {
                titleRow.createCell(titleIndex).setCellValue(keys.get(titleIndex));
              }
            }

            Log.d(this.getClass().toString(), "开始写入数据");
            HSSFRow dataRow = sheet.createRow(dataIndex + 1);
            for (int titleIndex = 0; titleIndex < allKeys.size(); titleIndex++) {
              Object valueToWrite = ondic.get(keys.get(titleIndex));
              Log.d(this.getClass().toString(), "写入第"+dataIndex+"行第"+titleIndex+"列数据为"+valueToWrite.toString());
              dataRow.createCell(titleIndex).setCellValue(valueToWrite.toString());
            }


          }else {
            Log.w(this.getClass().toString(), String.format("原生拿到的第%d 条数据不是字典，返回空串", dataIndex));
            result.success("");
          }
        }

        try {
          workbook.write(outputStream);
          outputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        result.success(filepath);
      }else {
        System.out.println("原生拿到的不是数组，返回空串");
        result.success("");
      }
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
    teardownEventChannels();
  }
}
